package com.mgq.netty.c6;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

public class TestByteBuf {

    public static void main(String[] args) {
        //netty 默认使用的directBuffer,也就是直接内存,不是堆内存
        //另外,4.1之后,非安卓平台默认开始池化功能. ByteBuf默认长度是256
        //当超过容量时,新增的长度小于512,每次新增16的倍数
        //如果大于512,则每次扩容是2^n
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.directBuffer();
        ByteBuf heapBuffer = ByteBufAllocator.DEFAULT.heapBuffer();
        System.out.println(byteBuf);
        System.out.println(heapBuffer);

        //ByteBuff的切片功能
        //ByteBuff的splice()方法是零拷贝,不会发生复制.

        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeBytes(new byte[]{'a','b','c','d','e','f','g','h','i','j'});

        ByteBuf buf1 = buffer.slice(0,5);
        ByteBuf buf2 = buffer.slice(5,10);
        log(buf1);
        log(buf2);
        buf1.setByte(0, 'b');
        log(buffer);
    }

    private static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf.toString());
    }
}
